package com.gyf.bos.web.action;

import com.gyf.bos.model.User;
import com.gyf.bos.service.IUserService;
import org.apache.struts2.ServletActionContext;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

public class UserAction extends BaseAction<User> {

    @Autowired
    private IUserService userService;


    public String login(){
        //1.获取参数
        String username = getModel().getUsername();
        String password = getModel().getPassword();

        HttpServletRequest request = ServletActionContext.getRequest();
        String serverCheckCode = (String) request.getSession().getAttribute("key");
        String clientCheckCode = request.getParameter("checkcode");
        if (serverCheckCode.equalsIgnoreCase(clientCheckCode)){
            //验证码正确
            User user = userService.login(username, password);
            if (user != null){
                System.out.println("登录成功");
                request.getSession().setAttribute("loginUser",user);
                return "home"; //主页面
            }else {
                System.out.println("登录失败，用户名或密码不正确");
                addActionError("登录失败，用户名或密码不正确");
                return "loginfailer";
            }
        }else {
            System.out.println("验证码错误");
            addActionError("登录失败，验证码错误");
            return "loginfailer";
        }
        //2.调用service
    }

    public String logout(){
        //1.获取参数
        ServletActionContext.getRequest().getSession().invalidate();
        return "login";
    }

    public String editPassword() throws IOException {
        User loginUser = (User) ServletActionContext.getRequest().getSession().getAttribute("loginUser");

        String newPwd = getModel().getPassword();

        String flag = "1";
        try {
            userService.modifyPasswprd(newPwd,loginUser.getId());

        } catch (Exception e) {
            flag = "0";
            e.printStackTrace();
        }

        //响应客户端端
        ServletActionContext.getResponse().setContentType("text/html;charset=UTF-8");
        ServletActionContext.getResponse().getWriter().print(flag);

        //返回json格式处理
//        response.setHeader("content-type","text/json;charset=utf-8");
//        response.getWriter().print("{\"success\":\"1\"}");

        return NONE;

    }

    @Override
    public String save() {
        return null;
    }

    @Override
    public String update() {
        return null;
    }

    @Override
    public String delete() {
        return null;
    }

    @Override
    public String list() {
        return null;
    }
}
